package com.sky.service.impl;

import com.alibaba.druid.filter.logging.Log4j2Filter;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.GDateBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private  OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;


    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        //获取时间
        List<LocalDate> dates = getDateList(begin,end);
        turnoverReportVO.setDateList(StringUtils.join(dates,","));
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dates) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalDateTime.MIN.toLocalTime());
            LocalDateTime endTime = LocalDateTime.of(date, LocalDateTime.MAX.toLocalTime());
            Double turnover = ordersMapper.turnoverStatistics(beginTime, endTime, Orders.COMPLETED);
            turnover=(turnover==null?turnover=0.0:turnover);
            turnoverList.add(turnover);
        }
        turnoverReportVO.setTurnoverList(StringUtils.join(turnoverList,","));
        return turnoverReportVO;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        UserReportVO userReportVO = new UserReportVO();
        //获得日期
        List<LocalDate> dates = getDateList(begin,end);
        userReportVO.setDateList(StringUtils.join(dates,","));
        //获得新用户列表，用户列表
        List<Integer> userList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        //获取begin前一天的用户总数
        Integer totalUser = userMapper.totalUser(LocalDateTime.of(begin, LocalDateTime.MIN.toLocalTime()));
        totalUser= (totalUser==null?totalUser=0:totalUser);
        System.out.println("\nbeginTime:"+begin+"\nuser:"+totalUser);
        for(LocalDate date : dates){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalDateTime.MIN.toLocalTime());
            LocalDateTime endTime = LocalDateTime.of(date, LocalDateTime.MAX.toLocalTime());
            Integer newUser = userMapper.totalnewUser(beginTime, endTime);
            newUserList.add(newUser);
            totalUser=totalUser+newUser;
            userList.add(totalUser);
        }
        userReportVO.setNewUserList(StringUtils.join(newUserList,","));
        userReportVO.setTotalUserList(StringUtils.join(userList,","));
        return userReportVO;
    }

    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        OrderReportVO orderReportVO = new OrderReportVO();
        List<LocalDate> dates = getDateList(begin,end);
        List<Integer> orderCompleteList = new ArrayList<>();
        List<Integer> orderTotalList = new ArrayList<>();
        //记录总数
        Integer totalOrder = 0;
        //记录完成数
        Integer completeOrder = 0;
        for (LocalDate date : dates) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalDateTime.MIN.toLocalTime());
            LocalDateTime endTime = LocalDateTime.of(date, LocalDateTime.MAX.toLocalTime());
            Integer orderTotal = ordersMapper.orderStatistics(beginTime, endTime, null);
            orderTotal = (orderTotal==null?orderTotal=0:orderTotal);
            orderTotalList.add(orderTotal);
            Integer orderComplete = ordersMapper.orderStatistics(beginTime, endTime, Orders.COMPLETED);
            orderComplete = (orderComplete==null?orderComplete=0:orderComplete);
            orderCompleteList.add(orderComplete);
            totalOrder = totalOrder + orderTotal;
            completeOrder = completeOrder + orderComplete;
        }
        orderReportVO.setDateList(StringUtils.join(dates,","));
        orderReportVO.setOrderCountList(StringUtils.join(orderCompleteList,","));
        orderReportVO.setValidOrderCountList(StringUtils.join(orderTotalList,","));
        orderReportVO.setTotalOrderCount(totalOrder);
        orderReportVO.setValidOrderCount(completeOrder);
        orderReportVO.setOrderCompletionRate(completeOrder/totalOrder.doubleValue());
        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO top10Statistics(LocalDate begin, LocalDate end) {
        begin=LocalDateTime.of(begin,LocalDateTime.MIN.toLocalTime()).toLocalDate();
        end=LocalDateTime.of(end,LocalDateTime.MAX.toLocalTime()).toLocalDate();
        List<Double> numberList = orderDetailMapper.salesnumberStatistics(begin, end);
        List<String> nameList = orderDetailMapper.salesnameStatistics(begin, end);

        // 继续处理keys和values，例如封装到SalesTop10ReportVO中
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(StringUtils.join(nameList,","));
        salesTop10ReportVO.setNumberList(StringUtils.join(numberList,","));
        return salesTop10ReportVO;
    }

    //导出营业报表
    @Override
    public void exportExcel(HttpServletResponse response) {
        //查询数据库
        LocalDateTime end = LocalDateTime.of(LocalDate.now(),LocalDateTime.MIN.toLocalTime());
        LocalDateTime begin= LocalDateTime.of(LocalDate.now().minusDays(30),LocalDateTime.MIN.toLocalTime());
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(begin,end);
        //导出excel
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            if (inputStream != null) {
                XSSFWorkbook excel = new XSSFWorkbook(inputStream);
                XSSFSheet sheet = excel.getSheet("Sheet1");
                //填充时间
                XSSFCell cell = sheet.getRow(1).getCell(1);
                cell.setCellValue("时间:"+begin+"至"+end);
                //填充数据
                cell= sheet.getRow(3).getCell(2);
                cell.setCellValue(businessDataVO.getTurnover());
                cell = sheet.getRow(3).getCell(4);
                cell.setCellValue(businessDataVO.getOrderCompletionRate());
                cell = sheet.getRow(3).getCell(6);
                cell.setCellValue(businessDataVO.getNewUsers());
                cell = sheet.getRow(4).getCell(2);
                cell.setCellValue(businessDataVO.getValidOrderCount());
                cell = sheet.getRow(4).getCell(4);
                cell.setCellValue(businessDataVO.getUnitPrice());

                //填充详细数据
                for (int i = 0; i < 30; i++) {
                    LocalDate date= LocalDate.from(begin.plusDays(i));
                    BusinessDataVO  data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalDateTime.MIN.toLocalTime()),LocalDateTime.of(date, LocalDateTime.MAX.toLocalTime()));
                    XSSFRow row =sheet.getRow(i+7);
                    row.getCell(1).setCellValue(date.toString());
                    row.getCell(2).setCellValue(data.getTurnover());
                    row.getCell(3).setCellValue(data.getValidOrderCount());
                    row.getCell(4).setCellValue(data.getOrderCompletionRate());
                    row.getCell(5).setCellValue(data.getUnitPrice());
                    row.getCell(6).setCellValue(data.getNewUsers());
                }

                //通过输出流下载到浏览器
                ServletOutputStream outputStream = response.getOutputStream();
                excel.write(outputStream);
                excel.close();
                outputStream.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    //获得日期List
    List<LocalDate> getDateList(LocalDate begin, LocalDate end){
        List<LocalDate> dates = new ArrayList<>();
        dates.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dates.add(begin);
        }
        return dates;
    }
}
